<script setup>
/**
 * @name 图文发布详情--抽屉
 */
    import { computed, reactive, ref, toRaw, watch, nextTick,inject } from 'vue'
    import { CloseOutlined, SearchOutlined, LeftOutlined, PlusOutlined } from '@ant-design/icons-vue'
    import { useTable } from '@/hooks/useTable'
    import { Form, message } from 'ant-design-vue'
    import _ from 'lodash'
    import request from '@/common/utils/request'
    import dayjs from 'dayjs'
    const { convertTimeToTimezone ,currentTimezone} = inject('timezone')
    const props = defineProps({
        visible: {
            type: Boolean,
            default: false
        },
        current_task_id: {
            type:[Number,String],
            default: ''
        },
        currentTask:{
            type: Object,
            default: () => {}
        },
        is_required_article_id: {
            type: Boolean,
            default: true
        }
    })
    const visible = computed({
        get: () => props.visible,
        set: (val) => {
            emit('update:visible', val)
        }
    })
    
    const emit = defineEmits(['update:visible', 'updateList'])
    let columns = ref([
    // {
    //     title: "序号",
    //     dataIndex: "article_id",
    //     key: "article_id",
    //     width: 100,
    // },
    // {
    //     title: "文章标题",
    //     dataIndex: "title",
    //     key: "title",

    // },
    {
        title: "发布平台",
        dataIndex: "platform_account_article_log",
        key: "platform_account_article_log", 
       
    },
    {
        title: "发布时间",
        dataIndex: "fix_at",
        key: "fix_at",
    },

    {
        title: "发布状态",
        dataIndex: "status_txt",
        key: "status_txt",
    },
    {
        title: "操作",
        dataIndex: "action",
        key: "action",
    },
])
    const cancel = ()=>{
        emit('update:visible', false)
    }
    let url = '/user/socialMedia/publishTask/article/list'
    let { list, pagination, getList, loading, page, pageSize,total } = useTable(url,5)
  
    const ok = ()=>{
      
    }
    const getDetail = ()=>{
        request.get('/work_ai', '/user/socialMedia/publishTask/info',{id:props.current_task_id}).then(res => {
            console.log(res,'xxxxxxxxxxxx');
        }).catch(err => {
            
        })
   }
    
    watch(()=>props.visible,(val)=>{
        let params = {
            id:props.current_task_id,
            date:props.currentTask?.fix_date,
            article_id:props.is_required_article_id?(props.currentTask?.article_id??0):0
          }
        
        val&&getList(params)

        if(!val){
            page.value = 1
            pageSize.value = 5
        }
       
    })
   const handleTableChange = (pagetion)=>{
        pageSize.value = pagetion.pageSize
        page.value = pagetion.current
        let params = {
            id:props.current_task_id,
            date:props.currentTask?.fix_date,
            article_id:props.is_required_article_id?(props.currentTask?.article_id??0):0
          }
        getList(params)
   }
   const rePublish = (record)=>{
    let params = {
        id:record.publish_task_id,
        article_id:record.article_id
    }
    
    request.post('/work_ai', '/user/socialMedia/publishTask/retry',params).then(res => {
            message.success('操作成功')
            let params = {
            id:props.current_task_id,
            date:props.currentTask?.fix_date,
            article_id:props.is_required_article_id?(props.currentTask?.article_id??0):0
            }
        getList(params)
          emit('updateList')
           
        }).catch(err => {
            
        })
   }
   let dayLog = ref(null)
   let logVisible = ref(false)
   const showLog = (record)=>{
    logVisible.value = true
    request.get('/work_ai', '/user/socialMedia/publishTask/info',{id:record.publish_task_id}).then(res => {
            dayLog.value = res?.result?.log??[]
        }).catch(err => {
            
        })
   }
   let column1 = ref(
    [
   
    {
        title: "发布平台",
        dataIndex: "platform_account_user",
        key: "platform_account_user",
    },
    {
        title: "发布账号",
        dataIndex: "account_id",
        key: "account_id",
    },
    {
        title: "发布状态",
        dataIndex: "status_txt",
        key: "status_txt",
    },
    // {
    //     title: "发布结果",
    //     dataIndex: "execute_json",
    //     key: "execute_json",
    // },
    {
        title: "计划发布时间",
        dataIndex: "fix_at",
        key: "fix_at",
    },

    
]
   )
   const isPublished = (publishTime)=>{
  return dayjs(publishTime).isBefore(dayjs())|| dayjs(publishTime).isSame(dayjs());
}
const isRePublish = (taskList) => {
    console.log(taskList,'taskListtaskList');
    
   return taskList?taskList.some(item=>item.status==3):false
}
const getIconList = (list)=>{
    let iconList = []
    iconList = list.map(item=>{
        return item?.platform_account_user?.platform?.image??''
    })
    iconList = Array.from(new Set(iconList))
    return iconList
}
const delTask = ()=>{
    request.del('/work_ai', '/user/socialMedia/publishTask/delete',{id:props.current_task_id}).then(res => {
        let params = {
            id:props.current_task_id,
            date:props.currentTask?.fix_date,
            article_id:props.currentTask?.article_id??0
          }
          getList(params)
          emit('updateList')
        }).catch(err => {
            
        }) 
}
const delAritcle = (record)=>{
    request.del('/work_ai', '/user/socialMedia/publishTask/delete',{article_id:record.article_id,id:props.current_task_id}).then(res => {
             let params = {
                id:props.current_task_id,
                date:props.currentTask?.fix_date,
                article_id:props.currentTask?.article_id??0
              }
             getList(params)
             emit('updateList')
        }).catch(err => {
            
        })  
}
let expandedRowKeys = ref([])

watch(()=>list,()=>{
    expandedRowKeys.value = list.value.map(item=>item.id)
},{deep:true})
</script>

<template>
    <a-drawer  width="1000px" :visible="visible" :footer="null" :destroyOnClose="true" @close="cancel">
        <template #title>
            <div class="title-wrapper">
                <div>{{ currentTask?.publish_task?.remark?currentTask?.publish_task?.remark:currentTask?.publish_task?.title }}</div>
               <a-popconfirm title="确认删除任务吗?" ok-text="确认" cancel-text="取消" @confirm="delTask" v-if="total>0">
                    <a-button type="primary" :disabled="total<=0">删除任务</a-button>
                </a-popconfirm>
                <a-button type="primary" :disabled="total<=0" v-else>删除任务</a-button>
            </div>
        </template>
        <div>
            <a-table row-key="id" v-model:expandedRowKeys="expandedRowKeys" :loading="loading" :dataSource="list" :columns="columns" :pagination="pagination" @change="handleTableChange" class="table">
            <template #bodyCell="{ index, column, text, record }">
                <template v-if="column.key == 'title'">
                    {{ record?.platform_account_article?.title }}
                </template>
                <template v-if="column.key == 'business_type'">
                    {{ record.business_type == '' ? '--' : record.business?.title??'--' }}
                </template>
                <template v-if="column.key == 'platform_account_article_log'">
                    <img :src="im" v-for="im in getIconList(text)"  class="icon-img mx-5 mb-5">
                </template>
                <template v-if="column.key == 'status_txt'">
                    {{  isPublished(record.fix_at)?'已发布':'未发布' }}
                </template>
                <template v-if="column.key == 'fix_at'">
                    {{ convertTimeToTimezone(text,(currentTask.publish_task?.utc_offset??currentTimezone)) }}
                </template>
                <template v-if="column.key == 'action'">
                   
                    <!-- <a-popconfirm title="确认删除文章吗?" ok-text="确认" cancel-text="取消" @confirm="delAritcle(record)">
                        <a-button  style="color:red" type="link">删除</a-button>
                    </a-popconfirm> -->
                    <a-button type="link" style="color:red" v-if="isRePublish(record.platform_account_article_log)" @click="rePublish(record)">重发</a-button>
                  
                </template>
            </template>
            <template #expandedRowRender="{ record }">
                <div class="table-wrapper">
                <a-table row-key="id" :dataSource="record.platform_account_article_log" :columns="column1" :pagination="false">
                    <template #bodyCell="{ index:i, column:col, text:selfData, record:item }">
                        <template v-if="col.key == 'platform_account_user'">
                            <a-tooltip>
                                <template #title>{{ selfData.source_txt }}</template>
                                <img :src="selfData?.platform?.image" class="icon-img">
                            </a-tooltip>
                        </template>
                        <template v-if="col.key == 'account_id'">
                            <span v-if="!item.deleted_at"> {{ item?.platform_account_user?.nickname }}</span>
                            <span v-else class="del-account">
                                <a-tooltip>
                                    <template #title>已删除</template>
                                    {{ item?.platform_account_user?.nickname }}
                                </a-tooltip>
                            </span>
                        </template>
                        <template v-if="col.key == 'fix_at'">
                            {{ convertTimeToTimezone(selfData,(currentTask.publish_task?.utc_offset??currentTimezone)) }}
                        </template>
                          <template v-if="col.key == 'status_txt'">
                            <div v-if="item.status==2" class="msg">{{ selfData }}</div>
                            <a-tooltip v-else>
                                <template #title>{{item?.execute_json?.msg??'--'}}</template>
                                <div :class="[0,1].includes(item.status)?'yellow':'error'">{{ selfData}}</div>
                            </a-tooltip>
                         </template>
                        <!-- <template v-if="col.key == 'execute_json'">
                        <a-tooltip>
                            <template #title>{{ selfData?.msg??'--' }}</template>
                            <div class="msg">{{ selfData?.msg??'--' }}</div>
                        </a-tooltip>
                        </template> -->
                    </template> 
                </a-table>
                 </div>
            </template>
        </a-table>
        </div>
         <!-- 日志 -->
        <a-modal title="日志" :width="800" v-model:visible="logVisible" :footer="null">
            <div class="log-list beauty-scroller-bar">
                <a-timeline>
                <a-timeline-item v-for="(item, index) in dayLog" :key="index">
                    <span class="mr-10">{{ item.created_at }}</span>
                    <span>{{ item.title }}</span>
                </a-timeline-item>
                </a-timeline>
            </div>
        </a-modal>
    </a-drawer>
</template>

<style lang="less" scoped>
.keywords-wrapper{
    min-height:100px;
    border:1px solid #ccc;
    padding:10px;
}  
.addkey{
    cursor: pointer;
} 
.icon-img{
    width: 30px;
    height: 30px;
}
.table-wrapper{
    padding: 10px 0;
    :deep(th){
        background-color: unset;
    }
}
.msg{
   max-width: 180px;
   overflow: hidden;
   text-overflow: ellipsis;
   white-space: nowrap;
   display: inline-block;
   cursor: pointer;
   color: var(--ss-primary-color);
}
.title-wrapper{
   display: flex;
   justify-content: space-between; 
   align-items: center; 
}
.del-account{
    color: #aaa;
    text-decoration: line-through;
    cursor: pointer;
}
.yellow{
    color:orange;
}
.error{
    color:red;
}
</style>